//
//  ZBTool.m
//  ZBUitilty
//
//  Created by xzb on 2018/8/22.
//

#import "ZBTool.h"

@implementation ZBTool

+ (void)onceEventForKey:(NSString *)key event:(void(^)(void))event
{
    id obj = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    if (!obj) {
        [[NSUserDefaults standardUserDefaults] setObject:@(1) forKey:key];
        if (event) {
            event();
        }
    }
}

+ (id)zb_safeForKey:(NSString *)key dict:(NSDictionary *)dict defaultValue:(id)defaultValue, ...
{
    if (key.length < 1 || !dict) {
        return defaultValue;
    }
    NSString *typeName;
    if ([defaultValue isKindOfClass:[NSString class]]) {
        va_list args;
        va_start(args, defaultValue);
        typeName = va_arg(args, id);
        va_end(args);
        if (![typeName isKindOfClass:[NSString class]]) {
            typeName = @"";
        }
    }
    if ([defaultValue isKindOfClass:[NSDictionary class]]) {
        return  [dict zb_safeDictionaryValueForKey:key defaultValue:defaultValue];
    }
    if ([defaultValue isKindOfClass:[NSString class]]) {
        return [dict zb_safeStringValueForKey:key defaultValue:defaultValue];
    }
    if ([defaultValue isKindOfClass:[NSArray class]]) {
        return [dict zb_safeArrayValueForKey:key defaultValue:defaultValue];
    }
    if ([defaultValue isKindOfClass:[NSNumber class]]) {
        return [dict zb_safeNumberValueForKey:key defaultValue:defaultValue];
    }
    if ([typeName isEqualToString:kEncode(NSUInteger)]) {
        return @([dict zb_safeUnsignedIntegerValueForKey:key defaultValue:[defaultValue unsignedIntegerValue]]);
    }
    if ([typeName isEqualToString:kEncode(NSInteger)]) {
        return @([dict zb_safeUnsignedIntegerValueForKey:key defaultValue:[defaultValue integerValue]]);
    }
    if ([typeName isEqualToString:kEncode(BOOL)]) {
        return @([dict zb_safeIntegerValueForKey:key defaultValue:[defaultValue boolValue]]);
    }
    if ([typeName isEqualToString:kEncode(CGFloat)]) {
        return @([dict zb_safeFloatValueForKey:key defaultValue:[defaultValue floatValue]]);
    }
    return defaultValue;
}


@end
